package com.personal.controller;

import cn.hutool.core.util.StrUtil;
import com.personal.bo.FindPasswordBO;
import com.personal.bo.LoginBO;
import com.personal.bo.UserBO;
import com.personal.enums.UserEnum;
import com.personal.exception.ExceptionUtils;
import com.personal.pojo.Users;
import com.personal.service.DynamicService;
import com.personal.service.UserService;
import com.personal.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@RestController
@RequestMapping("/passport")
@Api(tags = "用户相关接口")
public class PassportController {

    @Autowired
    private UserService userService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/usernameIsExist")
    @ApiOperation("判断用户名是否存在")
    public Result usernameIsExist(@RequestParam String username) {
        //判断用户名是否为空
        if (StringUtils.isBlank(username)) {
            ExceptionUtils.error(UserEnum.USERNAME_IS_NULL);
        }
        //查询注册的用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist){
            ExceptionUtils.error(UserEnum.USERNAME_EXIST);
        }
        //请求成功
        return Result.success();
    }

    @PostMapping("/regist")
    @ApiOperation("注册")
    public Result regist(@RequestBody UserBO userBO,
                         HttpServletRequest request,
                         HttpServletResponse response) {

        String username = userBO.getUsername();
        String password = userBO.getPassword();
        String emailCode = userBO.getEmailCode();
        String email = userBO.getEmail();

        //判断用户名是不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password) ||
                StringUtils.isBlank(email) ||
                StringUtils.isBlank(emailCode)) {
            ExceptionUtils.error(UserEnum.REGIST_PARAMETER_IS_NULL);
        }

        //查询用户是否存在
        //查询注册的用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist){
            ExceptionUtils.error(UserEnum.USERNAME_EXIST);
        }

        //密码长度不能小于6位
        if (password.length() < 6){
            ExceptionUtils.error(UserEnum.PASSWORD_LEN_LONGER);
        }

        //判断验证码是否正确
        //通过邮箱获取到验证码
        String code = (String) redisUtils.get(userBO.getEmail());
        if (StrUtil.isBlank(code) || !userBO.getEmailCode().equals(code)){
            ExceptionUtils.error(UserEnum.EMAIL_CODE_ERROR);
        }else {
            redisUtils.del(userBO.getEmail());
        }

        //实现注册
        Users userResult = userService.createUser(userBO);

        userResult = setNullProperty(userResult);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userResult), true);

        return Result.success("注册成功");
    }

    @PostMapping("/login")
    @ApiOperation("登录")
    public Result login(@RequestBody LoginBO loginBO,
                        HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
        String username = loginBO.getUsername();
        String password = loginBO.getPassword();

        //判断用户名是不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)) {
            ExceptionUtils.error(UserEnum.USER_OR_PASSWORD_ERROR);
        }

        //实现登录（todo 使用策略模式重构登录，方便后续添加不同的登录方式）
        Users userResult = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));
        userResult = setNullProperty(userResult);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userResult), true);

        //todo 生成用户token，存入redis中缓存
        //todo，更新购物车数据

        return Result.success(userResult);
    }

    @GetMapping("/sendEmail")
    @ApiOperation("发送邮箱验证码")
    public Result seadEmail(@RequestParam("email") String email){
        //判断邮箱是否为空
        if (StringUtils.isBlank(email)){
            ExceptionUtils.error(UserEnum.EMAIL_IS_NULL);
        }

        //判断邮箱格式是否正确
        if (!MobileEmailUtils.checkEmailIsOk(email)){
            ExceptionUtils.error(UserEnum.EMAIL_FORMAT_NOT_TRUE);
        }

        userService.seadEmailCode(email);

        return Result.success("发送成功");
    }


    @PostMapping("/logout")
    @ApiOperation("登出")
    public Result logout(@RequestParam("userId") String userId,
                        HttpServletRequest request,
                        HttpServletResponse response) throws Exception {

        CookieUtils.deleteCookie(request, response, "users");

        return Result.success("你已登出");
    }

    @PostMapping("/findPassword")
    @ApiOperation("找回密码")
    public Result findPassword(@Valid @RequestBody FindPasswordBO findPasswordBO){
        return userService.findPassword(findPasswordBO);
    }

    private Users setNullProperty(Users userResult){
        userResult.setPassword(null);
        userResult.setPhone(null);
        userResult.setEmail(null);
        userResult.setCreateTime(null);
        userResult.setUpdateTime(null);
        userResult.setBirthday(null);

        return userResult;
    }

}
